import React, { Component } from 'react';
import { Input } from 'antd';
import PropTypes from 'prop-types';

import { TRMessage } from '#/components';
import { CloseCircleFilled } from '#/utils/antdIcons';
import { isTRArray } from '#/utils/attribute';
import { overMaxMessage, precisionReg, point } from './Helper';
import styles from './index.less';

export class TRInputMinus extends React.Component {
  __tempText__ = '';
  static defaultProps = {
    text: '',
    isFocus: false,
  };
  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.isFocus) {
      return null;
    }
    if (nextProps.text !== prevState.value) {
      return { value: nextProps.text, orgintext: nextProps.text };
    }
    return null;
  }
  constructor(props) {
    super(props);
    this.state = {
      value: this.props.text,
      orgintext: this.props.text,
    };
  }
  _onFocus() {
    this.__tempText__ == this.state.value;
    this.setState({
      isFocus: true,
    });
  }
  async _onBlur() {
    if (this.__tempText__ === this.state.value) {
      if (this.state.value === '' || this.state.value === '-') {
        await this.setState({
          value: this.state.orgintext,
        });
      }
    }
    const { onChange, cellItem, keyVal } = this.props;
    this.state.value !== '-' &&
      onChange &&
      onChange(String(this.state.value).split(/[\s+\n\f\r]/), keyVal, cellItem);
    let tep = {};
    if (this.state.value === '') {
      tep.value = parseFloat(this.state.orgintext);
    }
    this.setState({
      isFocus: false,
      ...tep,
    });
  }
  onChange(event) {
    if (event && event.target) {
      const { clipboardData } = this.state;
      const { onChange, cellItem, keyVal } = this.props;
      let hasF = false;
      let str = event.target.value || '';
      if (str[0] === '-') {
        hasF = true;
      }
      if (Number(event.target.value) < -999999999 || Number(event.target.value) > 999999999) {
        str = this.state.value;
      }

      if (clipboardData && clipboardData.length > 0) {
        if (isTRArray(clipboardData)) {
          let isNumberFlag = clipboardData.some((item) => {
            if (item) {
              return Number.isNaN(Number(item));
            } else {
              return Number.isNaN(Number('空格'));
            }
          });
          if (isNumberFlag) {
            TRMessage.error('粘贴内容应为数值,请检查后重试');
            this.setState({ clipboardData: [] });
            return;
          }
        }
        let inputValue = clipboardData[0];
        str = String(inputValue);
        onChange && onChange(clipboardData, keyVal, cellItem);
        this.setState({
          isFocus: true,
          value: inputValue,
          clipboardData: '',
        });
      }

      if (this.props.precision === (6 || '6')) {
        this.setState({
          isFocus: true,
          value: (hasF ? '-' : '') + str.replace(/^\D*(\d*(?:\.\d{0,6})?).*$/g, '$1'),
        });
      } else {
        this.setState({
          isFocus: true,
          value: (hasF ? '-' : '') + str.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1'),
        });
      }
    }
  }

  //拿取粘贴版信息
  handlePaste = async (e) => {
    if (e.clipboardData) {
      let value = e.clipboardData.getData('Text').trim();
      let hiddenInputValue =
        value.indexOf('\\n') >= 0 ? value.replace(/[\s+]/g, ';') : value.replace(/[\r\n]/g, ';');

      let valueSplit =
        hiddenInputValue.indexOf(';;') > -1
          ? hiddenInputValue
          : hiddenInputValue.replace(/\s{1,}/g, ';');
      await this.setState({
        clipboardData:
          hiddenInputValue.indexOf(';;') > -1
            ? hiddenInputValue.split(';;')
            : valueSplit.indexOf(';') > -1
            ? valueSplit.split(';')
            : valueSplit.split(/[\s+\n\f\r]/g),
      });
    }
  };

  render() {
    const { precision, inputStyle = {}, lockImgStyle = {} } = this.props;
    if (this.props.disabled) {
      let width = Object.keys(lockImgStyle).length > 0 ? 'auto' : precision === 6 ? '75px' : '45px';
      let marginRight =
        Object.keys(lockImgStyle).length > 0
          ? { marginRight: '10px', marginLeft: 18 }
          : { width: precision === 6 ? '75px' : '45px', marginRight: 0, marginLeft: 0 };
      return (
        <div className={styles.inputboxtext} style={{ width, ...marginRight }}>
          {Number(this.state.value).toFixed(precision)}
        </div>
      );
    }
    return (
      <div className={styles.inputbox}>
        <Input
          ref={(e) => (this._input = e)}
          style={{ padding: 0, textAlign: 'center', ...inputStyle }}
          onPressEnter={() => {
            this._input && this._input.blur();
          }}
          value={this.state.value}
          disabled={this.props.disabled}
          onFocus={this._onFocus.bind(this)}
          onBlur={this._onBlur.bind(this)}
          onChange={this.onChange.bind(this)}
          onPaste={this.handlePaste}
        />
      </div>
    );
  }
}

export class TRInputPlus extends Component {
  __tempText__ = '';
  static defaultProps = {
    text: '',
    isFocus: false,
  };
  static getDerivedStateFromProps(nextProps, prevState) {
    if (prevState.isFocus) {
      return null;
    }
    if (nextProps.text !== prevState.value) {
      return { value: nextProps.text, orgintext: nextProps.text };
    }
    return null;
  }
  constructor(props) {
    super(props);
    this._hiddenInput = React.createRef();
    this.state = {
      value: this.props.text,
      orgintext: this.props.text,
      clipboardData: null,
    };
  }
  _onFocus() {
    this.__tempText__ == this.state.value;
    this.setState({
      isFocus: true,
    });
  }
  _onBlur() {
    const { onChange, cellItem, keyVal } = this.props;
    if (this.__tempText__ === this.state.value) {
      if (this.state.value === '') {
        this.setState({
          value: this.state.orgintext,
        });
        this.__tempText__ = this.state.orgintext;
      }
    }

    const { value, clipboardData } = this.state;
    if (!clipboardData && value) {
      onChange && onChange(String(value).split(/[\s+\n\f\r]/), keyVal, cellItem, false);
    }

    let tep = {};
    if (this.state.value === '') {
      tep.value = parseFloat(this.state.orgintext);
    }
    this.setState({
      isFocus: false,
      ...tep,
      clipboardData: '',
    });
  }

  onChange(event) {
    if (event && event.target) {
      const { onChange, cellItem, keyVal, maxCapacity, dataList, precision } = this.props;
      const { clipboardData } = this.state;
      let str = event.target.value || '';
      if (Number(event.target.value) < 0 || Number(event.target.value) > 999999999) {
        str = this.state.value;
      }
      if (clipboardData && clipboardData.length > 0) {
        let len = 0;
        if (isTRArray(clipboardData)) {
          len = clipboardData.length;
          let isNumberFlag = clipboardData.some((item) => {
            if (item) {
              if (Number(item) < 0) {
                return true;
              } else {
                return Number.isNaN(Number(item));
              }
            } else {
              return Number.isNaN(Number('空格'));
            }
          });
          if (isNumberFlag) {
            TRMessage.error('粘贴内容应为正数数值,请检查后重试');
            return;
          }
        }
        //超出最大值的时间点值的集合
        let overMaxCapacityArr = [];
        dataList.map((item) => {
          let _keys = Object.keys(item);
          let valueIndex = _keys.findIndex((value) => value == keyVal); //单元格索引
          let timerKeyArr = _keys.slice(valueIndex, valueIndex + len); //从当前单元格截取
          timerKeyArr.filter((timeKey, index) => {
            let timeKeyValue = point(
              Number(clipboardData[index].replace(precisionReg, '$1')),
              precision,
            );
            if (maxCapacity && maxCapacity < timeKeyValue) {
              timeKeyValue = maxCapacity;
              overMaxCapacityArr.push(timeKey);
            }
          });
        });

        let inputValue =
          Number(maxCapacity) < Number(clipboardData[0]) ? maxCapacity : clipboardData[0];
        this.setState(
          {
            isFocus: true,
            value: inputValue,
            clipboardData: '',
          },
          () => {
            const { powerAndelectricId } = this.props;

            if (powerAndelectricId) {
              if (maxCapacity && overMaxCapacityArr.length > 0) {
                this.messageInfo(
                  maxCapacity,
                  Array.from(new Set(overMaxCapacityArr)),
                  powerAndelectricId,
                );
              }
            }
          },
        );
        str = String(inputValue);
        onChange && onChange(clipboardData, keyVal, cellItem, true);
      }
      if (this.props.precision === (6 || '6')) {
        this.setState({
          isFocus: true,
          value: str.replace(/^\D*(\d*(?:\.\d{0,6})?).*$/g, '$1'),
        });
      } else {
        this.setState({
          isFocus: true,
          value: str.replace(/^\D*(\d*(?:\.\d{0,3})?).*$/g, '$1'),
        });
      }
    }
  }

  messageInfo(maxCapacity, overMaxCapacityArr, powerAndelectricId) {
    let message = (
      <div
        style={{ maxWidth: 600, wordWrap: 'break-word', wordBreak: 'break-all', display: 'flex' }}
      >
        <CloseCircleFilled twoToneColor="#f00" />
        {overMaxMessage(maxCapacity, overMaxCapacityArr, powerAndelectricId)}
      </div>
    );
    TRMessage.error(message);
  }

  //拿取粘贴版信息
  handlePaste = async (e) => {
    if (e.clipboardData) {
      let value = e.clipboardData.getData('Text').trim();
      let hiddenInputValue =
        value.indexOf('\\n') >= 0 ? value.replace(/[\s+]/g, ';') : value.replace(/[\r\n]/g, ';');

      let valueSplit =
        hiddenInputValue.indexOf(';;') > -1
          ? hiddenInputValue
          : hiddenInputValue.replace(/\s{1,}/g, ';');
      await this.setState({
        clipboardData:
          hiddenInputValue.indexOf(';;') > -1
            ? hiddenInputValue.split(';;')
            : valueSplit.indexOf(';') > -1
            ? valueSplit.split(';')
            : valueSplit.split(/[\s+\n\f\r]/g),
      });
    }
  };

  render() {
    const { precision } = this.props;
    if (this.props.disabled) {
      return (
        <div className={styles.inputboxtext} style={{ width: precision === 6 ? '75px' : '45px' }}>
          {Number(this.state.value).toFixed(precision)}
        </div>
      );
    }

    return (
      <div className={styles.inputbox}>
        <Input
          ref={(e) => (this._input = e)}
          style={{ padding: 0, textAlign: 'center' }}
          onPressEnter={() => {
            this._input && this._input.blur();
          }}
          value={this.state.value}
          disabled={this.props.disabled}
          onFocus={this._onFocus.bind(this)}
          onBlur={this._onBlur.bind(this)}
          onChange={this.onChange.bind(this)}
          onPaste={this.handlePaste}
        />
      </div>
    );
  }
}

TRInputPlus.propTypes = {
  text: PropTypes.string,
  onChange: PropTypes.func,
  cellItem: PropTypes.object,
  keyVal: PropTypes.node,
  maxCapacity: PropTypes.oneOfType([PropTypes.string, PropTypes.string]),
  precision: PropTypes.oneOfType([PropTypes.string, PropTypes.string]),
  dataList: PropTypes.array,
  disabled: PropTypes.bool,
  powerAndelectricId: PropTypes.number,
};

TRInputMinus.propTypes = {
  text: PropTypes.string,
  onChange: PropTypes.func,
  cellItem: PropTypes.object,
  keyVal: PropTypes.node,
  inputStyle: PropTypes.object,
  lockImgStyle: PropTypes.object,
  disabled: PropTypes.bool,
};
